package com.young.springdemo.config;

import org.omg.PortableServer.THREAD_POLICY_ID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncTaskConfigure  {

    private final static Logger logger = LoggerFactory.getLogger(AsyncTaskConfigure.class);
    /**
     *   默认情况下，在创建了线程池后，线程池中的线程数为0，当有任务来之后，就会创建一个线程去执行任务，
     *    当线程池中的线程数目达到corePoolSize后，就会把到达的任务放到缓存队列当中；
     *  当队列满了，就继续创建线程，当线程数量大于等于maxPoolSize后，开始使用拒绝策略拒绝
     */

    /** 核心线程数（默认线程数） */

    @Bean("myTask")
    public ThreadPoolTaskExecutor taskExecutor(){
        logger.debug("create Young-def thread");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数（默认线程数）
        taskExecutor.setCorePoolSize(10);
        //最大线程数
        taskExecutor.setMaxPoolSize(50);
        //缓冲队列大小
        taskExecutor.setQueueCapacity(20);

        taskExecutor.setAllowCoreThreadTimeOut(false);
        //线程池名称
        taskExecutor.setThreadNamePrefix("young-executor-");
        //允许线程空闲时间(单位: sec)
        taskExecutor.setKeepAliveSeconds(600);
        //线程池对拒绝任务的处理策略
        //CallRunsPolicy:由调用线程(提交任务的线程)处理该任务.
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        //初始化
        taskExecutor.initialize();
        return taskExecutor;
    }

}
